package com.example.admin.servicetest;

import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class SecondActivity extends AppCompatActivity {
    private String TAG = this.getClass().getSimpleName();
    private MyServiceConnection myServiceConnection = new MyServiceConnection();
    private TextView tvMsg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.i(TAG, "onCreate()");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        EventBus.getDefault().register(this);
        tvMsg = findViewById(R.id.tv_msg);

    }

    public void startService(View view) {
        Intent intent = new Intent(this, MyService.class);
        startService(intent);
    }

    public void stopService(View view) {
        Intent intent = new Intent(this, MyService.class);
        stopService(intent);
    }

    public void bindService(View view) {
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, myServiceConnection, Service.BIND_AUTO_CREATE);
    }

    public void unBindService(View view) {
        unbindService(myServiceConnection);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMsgReceived(SimpleEvent simpleEvent) {
        tvMsg.setText(simpleEvent.getMsg());
    }

    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected()");
            IMyAidlInterface iMyAidlInterface = IMyAidlInterface.Stub.asInterface(service);
//            try {
//                MyService.MyBinder myBinder = (MyService.MyBinder) iMyAidlInterface;
//                Log.i(TAG, "myBinder==null?" + (myBinder == null));
//            } catch (ClassCastException exception) {
//               exception.printStackTrace();
//            }
            try {
                iMyAidlInterface.sendMsg("hello,Service,I have connected you");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected()");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
